#include <iostream>
#include <signal.h>
#include <unistd.h>

void Print_Pending(sigset_t set)
{
    for (int signo = 31; signo >= 1; signo--)
    {
        if (sigismember(&set, signo))
        {
            std::cout << "1";
        }
        else
        {
            std::cout << "0";
        }
    }
    std::cout << std::endl;
}

void handler(int signum)
{
    std::cout << "------------------------entery handler" << std::endl;
    sigset_t pending;
    sigemptyset(&pending);
    // 2. 获取pending表
    int n = sigpending(&pending);
    (void)n;
    Print_Pending(pending);
    std::cout << "处理完成： " << signum << std::endl; // 更改2号的默认终止行为，改为打印
    std::cout << "------------------------leave handler" << std::endl;
}

int main()
{
    std::cout << "pid: " << getpid() << std::endl;

    signal(2, handler);
    sigset_t block_set, old_set;
    sigemptyset(&block_set);
    sigemptyset(&old_set);
    sigaddset(&block_set, 2);

    // 设置2号信号阻塞
    int n = sigprocmask(SIG_SETMASK, &block_set, &old_set);
    (void)n;
    int cnt = 1;
    while (true)
    {
        sigset_t pending;
        sigemptyset(&pending);
        // 获取pending表
        n = sigpending(&pending);
        (void)n;
        Print_Pending(pending);
        
        if(cnt == 20)
        {
            std::cout << "解除对2号信号屏蔽" << std::endl;
            int n = sigprocmask(SIG_SETMASK,&old_set,nullptr);
            (void)n;
        }
        cnt++;
        sleep(1);
    }

    return 0;
}